<script setup>
import useUserStore from '@/stores/user.js'
import { deleteFile, httpUploadFile } from '@/api/file.js'
import { uploadError } from '@/utils/index.js'
import { ElMessageBox, ElMessage, ElLoading } from 'element-plus'
import { reactive, ref } from 'vue'
import { changePassword } from '@/api/user.js'
import ImageCorpper from '@/components/image-corpper/index.vue'

const imagePrefix = import.meta.env.VITE_IMAGE_SUFFIX
const userStore = useUserStore()
const uploadUrl = import.meta.env.VITE_BASE_API + '/upload/image'
const uploadRef = ref(null)
const handleLogout = async () => {
  const confirm = await ElMessageBox.confirm('确认退出登录？', '确认提示').then(() => true).catch(() => false)
  if (confirm) {
    userStore.logout()
    location.reload()
  }
}

const uploadSuccess = async (data, uploadEl) => {
  if (data.code === 200) {
    const { file_id } = data.data
    const old_avatar = userStore.info.avatar
    const result = await userStore.setAvatar(file_id)
    if (result && old_avatar) {
      await deleteFile(old_avatar)
    }
    uploadEl.clearFiles()
  } else {
    ElMessage.error(data.message)
  }
  ElLoading.service({ fullscreen: true }).close()
}


const data = reactive({
  pwd_old: '',
  pwd_new: '',
  pwd_new_c: '',
})

const validateNewPwd = (rule, value, callback) => {
  if (value.length < 6) {
    return callback(new Error('密码长度不能小于6位'))
  }
  if (value === data.pwd_old) {
    return callback(new Error('新密码不能与原密码相同'))
  }
  return callback()
}

const validateNewPwdConfirm = (rule, value, callback) => {
  if (value !== data.pwd_new) {
    return callback(new Error('两次密码输入不一致'))
  }
  return callback()
}

const changePwdForm = ref(null)
const showDialog = ref(false)

const rules = {
  pwd_old: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
  pwd_new: [{ required: true, message: '请输入新密码', trigger: 'blur' },
    { validator: validateNewPwd, trigger: 'blur' },
  ],
  pwd_new_c: [
    { validator: validateNewPwdConfirm, trigger: 'blur' },
  ],
}

const loading = ref(false)

const handleSubmit = async (formEl) => {
  const valid = await formEl.validate(valid => valid)
  if (!valid) return
  loading.value = true
  const result = await changePassword({ ...data }).then(() => true).catch(() => false)
  loading.value = false
  if (result) {
    ElMessage.success('修改成功')
    showDialog.value = false
  }
}

const isShowCorpper = ref(false)
const selectPic = ref('')

const beforeUpload = (file) => {
  let type_arr = ['image/jpeg', 'image/png']
  let type = file.type
  if (!type_arr.includes(type)) {
    ElMessage.error('图片格式不正确,只支持jpg和png类型图片')
    return false
  }
  const reader = new FileReader()
  reader.readAsDataURL(file)
  reader.onload = () => {
    selectPic.value = String(reader.result)
    isShowCorpper.value = true
  }
  return false
}

const hideCorpper = (data) => {
  isShowCorpper.value = false
  if (data) {
    const { file } = data
    // userStore.info.avatar = dataURL
    uploadAvatar(file)
  }
}

const uploadAvatar = async (file) => {
  ElLoading.service({ fullscreen: true, text: '头像上传中...' })
  const response = await httpUploadFile(file).catch(() => null)
  if (response) {
    await uploadSuccess({ code: 200, data: response }, uploadRef.value)
  }
}

</script>

<template>
  <el-form label-width="120" class="margin-top-30">
    <el-form-item>
      <template #label>
        <div class="h-100 flex align-items-center">头像：</div>
      </template>
      <div class="my-avatar w-100 h-100 flex justify-content-center align-items-center border-radius pointer">
        <el-image
          v-if="userStore.info.avatar"
          :src="imagePrefix + userStore.info.avatar"
          fit="cover"
          :preview-src-list="[imagePrefix + userStore.info.avatar]"
          class="pw-100 ph-100"
        />
        <el-icon v-else style="font-size: 88px">
          <component is="Avatar" />
        </el-icon>
      </div>
      <el-upload
        ref="uploadRef"
        auto-upload
        :limit="1"
        :action="uploadUrl"
        :before-upload="beforeUpload"
        :on-error="uploadError"
        :on-success="(d) => uploadSuccess(d, uploadRef)"
        :show-file-list="false"
      >
        <el-button type="warning" icon="Upload" class="margin-left-20">上传</el-button>
      </el-upload>

    </el-form-item>
    <el-form-item :label="userStore.info.type === 1 ? '学号：' : '工号：'">
      <el-text>{{ userStore.info.code }}</el-text>
    </el-form-item>
    <el-form-item label="姓名：">
      <el-text>{{ userStore.info.name }}</el-text>
    </el-form-item>
    <el-form-item label="" label-width="70">
      <div class="h-100 pw-100"></div>
      <el-button type="danger" @click="handleLogout">退出登录</el-button>
      <el-button type="warning" @click="() => {showDialog = true}">修改密码</el-button>
    </el-form-item>
  </el-form>
  <el-dialog
    v-model="showDialog"
    :close-on-click-modal="false"
    :title="`修改登录密码`"
    width="400px"
    top="10vh"
    draggable
    center
  >
    <el-form
      ref="changePwdForm"
      class="login-form padding-30 margin-top-30 border-radius-xl"
      :rules="rules"
      :label-width="0"
      :model="data"
    >
      <el-form-item prop="pwd_old">
        <el-input
          type="password"
          size="large"
          clearable
          :placeholder="`输入原密码`"
          v-model="data.pwd_old"
          prefix-icon="Lock"
          @keyup.native.enter="handleSubmit(changePwdForm)"
        />
      </el-form-item>
      <el-form-item prop="pwd_new">
        <el-input
          type="password"
          size="large"
          clearable
          :placeholder="`输入新密码`"
          v-model="data.pwd_new"
          prefix-icon="Lock"
          @keyup.native.enter="handleSubmit(changePwdForm)"
        />
      </el-form-item>
      <el-form-item prop="pwd_new_c">
        <el-input
          type="password"
          size="large"
          clearable
          :placeholder="`确认新密码`"
          v-model="data.pwd_new_c"
          prefix-icon="Lock"
          @keyup.native.enter="handleSubmit(changePwdForm)"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          size="large"
          type="primary"
          class="pw-100 margin-top-20"
          @click="handleSubmit(changePwdForm)"
          :loading="loading"
        >修 改
        </el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
  <image-corpper :visible="isShowCorpper" :image="selectPic" @close="hideCorpper" :isCompress="true" />
</template>

<style scoped>
.my-avatar {
  overflow: hidden;
  background-color: var(--el-bg-color-page);
  color: var(--el-color-info);
}
</style>